package com.oneandseven.dajia.openai;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


import java.util.List;


public class OpenAiClient {

    List<ChatCompletionsRequest.ChatRequestMessage> messages;
    private String baseUrl;
    private String secretKey;
    private final CloseableHttpClient httpclient;

    private final ObjectMapper objectMapper;

    public OpenAiClient(String baseUrl, String secretKey) {
        this.baseUrl = baseUrl;
        this.secretKey = secretKey;
        this.httpclient = HttpClients.createDefault();
        this.objectMapper = new ObjectMapper();
    }

    public ChatCompletion getChatCompletion(ChatCompletionsRequest chatCompletionsRequest) throws Exception {
        String chatCompletionsRequestData = objectMapper.writeValueAsString(chatCompletionsRequest);
        HttpPost httpPost = new HttpPost(baseUrl + "/chat/completions");
        httpPost.addHeader("Authorization", "Bearer " + secretKey);
        httpPost.addHeader("Content-type", "application/json");
        HttpEntity stringEntity = new StringEntity(chatCompletionsRequestData, ContentType.APPLICATION_JSON);
        httpPost.setEntity(stringEntity);
        try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            String responseData = EntityUtils.toString(entity2,"UTF-8");
            return objectMapper.readValue(responseData, ChatCompletion.class);
        }
    }

    // Getters and setters for baseUrl and secretKey if needed
    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }
}